<?php

/**
 * tree actions.
 *
 * @package    sf_sandbox
 * @subpackage tree
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class treeActions extends autotreeActions
{

    public function executeIcon()
    {
        if ($this->getRequestParameter('uname'))
        {
            $uname = Files::getNameFromUrl($this->getRequestParameter('uname'));
            $c = new Criteria();
            $c->add(FilesPeer::OBJ_TYPE, MyConstants::TYPE_TREE_PAGE);
            $c->add(FilesPeer::UNAME, $uname);
            $file = FilesPeer::doSelectOne($c);
            $id = $file->getObjId();
//            debugvar($file, 'File w/ ID: ' . $id);
            Files::deleteByUname($file->getUname(), true);
            return $this->redirect('tree/icon?id=' . $id);
        }
        
        $this->id = (int)$this->getRequestParameter('id');
        $c = new Criteria();
        $c->add(FilesPeer::OBJ_ID, $this->id);
        $c->add(FilesPeer::OBJ_TYPE, MyConstants::TYPE_TREE_PAGE);
        $this->icon = FilesPeer::doSelectOne($c);

        // If user uploads photo
        if($this->getRequest()->hasFiles())
        {
            // remove old icon, if exists
            if($this->icon)
            {
                $this->icon->delete();
                //debugvar((sfConfig::get('sf_upload_dir').'/'.$this->icon->getRealName()) . 'kkkk');
//                exit('deleted...');
            }
            $fileName = $this->getRequest()->getFileName('file');
            
            $bExt = substr($fileName, strrpos($fileName, '.') + 1);
            $ext = strtolower($bExt);
            $uname = md5('treepage-' . MyConstants::TYPE_TREE_PAGE . '-' . $this->id) . '.' . $ext;
            $this->getRequest()->moveFile('file', Files::getDirPath('tiny', true) . $uname);
            
            $file = new Files();
            $file->setRealName($fileName);
            $file->setUserId(get_user_id());
            $file->setObjId($this->id);
            $file->setObjType(MyConstants::TYPE_TREE_PAGE);
            $file->setUname($uname);
//            $file->setCulture($this->getUser()->getCulture());
            //debugvar($file);
            $file->save();
            $this->setFlash('notice', 'Your modifications have been saved');
            return $this->redirect('tree/icon?id=' . $this->id);
        }
        
    }

    public function executeTest()
    {
        $lv = ListValues::getValueByParentLabel('DIAMETER', 17);
        debugvar($lv, 'Diameter 17"');
        
        
//        $parentId = (int)$this->getRequestParameter('id', 0);
//
//        if( $parentId )
//            $this->arBranch = Tree::getTree($parentId);
//        else
//            $this->arBranch = Tree::getTreeByLabel('photos');

        //debugvar($this->arBranch, 'Before prioritizing');

        //$ar = $this->arBranch;
        //Tree::applyPriority($ar);

//        $ar = array();
//        $ar[0]['obj'] = new Tree();
//        $ar[0]['obj']->setId(1);
//        $ar[0]['obj']->setPriority(1);
//
//        $ar[1]['obj'] = new Tree();
//        $ar[1]['obj']->setId(2);
//        $ar[1]['obj']->setPriority(2);
//
//        $ar[2]['obj'] = new Tree();
//        $ar[2]['obj']->setId(3);
//        $ar[2]['obj']->setPriority(1);
//
//        $ar[3]['obj'] = new Tree();
//        $ar[3]['obj']->setId(4);
//        $ar[3]['obj']->setPriority(4);
//
//        Tree::applyPriority($ar);

        //debugvar($this->arBranch, 'After prioritizing');
        exit();
    }

    public function executeDump()
    {
        $parentId = (int)$this->getRequestParameter('id', 0);
        $label = $this->getRequestParameter('label');

        if( $label )
            $arBranch = Tree::getTreeByLabel($label);
        else
            $arBranch = Tree::getTree($parentId);

        debugvar($arBranch);
        if( ( $bId = (int)$this->getRequestParameter('bId', 0) ) )
            debugvar(Tree::getBranchById($bId, $this->getUser()->getCulture()));
        exit();
    }

    public function executeTree()
    {
        $this->level = 1;
        $this->arBranch = Tree::getTree('1');
    }

    public function executeMoveup()
    {
        $userId = $this->getUser()->getAttribute('userId');
        $this->forwardUnless($userId, 'system', 'login');

        $objId = (int)$this->getRequestParameter('id', 0);
        if( !$objId )
        {
            $this->redirect('tree/list');
        }

        $parent = Tree::getParentByChild($objId);
        if( $parent != null )
        {
            $c = new Criteria();
            $c->add(TreePeer::PARENT_ID, $parent->getId());
            //debugvar('Moving up: ' . $objId);
            APriority::moveUp($c, $objId);
        }

        $this->forward('tree', 'list');
    }

    public function executeSelectmodule()
    {
        $objId = (int)$this->getRequestParameter('id', 0);
        $this->tree = TreePeer::retrieveByPk($objId);
        $this->forward404Unless($this->tree);
    }

    public function executeResetmodule()
    {
        $objId = (int)$this->getRequestParameter('id', 0);
        $tree = TreePeer::retrieveByPk($objId);
        $this->forward404Unless($tree);
        // drop old module by deleting tree branch
        Tree::deleteObjByType($tree->getObjType(), $tree->getObjId()); 
        $tree->setObjId(0);
        $tree->setObjType(MyConstants::MODULE_VIRTUAL);
        $tree->save();
        $this->redirect('tree/selectmodule?id=' . $tree->getId());
    }
    
    public function executeLinkto()
    {
        /* @var $tree Tree */
        $id = (int)$this->getRequestParameter('id', 0);
        $tree = TreePeer::retrieveByPk($id);
        $this->forward404Unless($tree);
        
        $options =  array(
            'is_external' => 0
        );
        
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            // changing type of tree object to link
            $tree->setObjType(MyConstants::TYPE_LINK_TO);
            
            $isExternal = (int)$this->getRequestParameter('options[is_external]');
            if( $isExternal )
            {
                $options['is_external'] = 1;
            }
            if( ($link = $this->getRequestParameter('tree[link_to]')) )
            {
                $tree->setLinkTo($link);
            }
            
            $tree->setOptionsJson(json_encode($options));
            $tree->save();
            
            
            return $this->redirect('tree/linkto?id=' . $id);
        }
        
        $this->options = $tree->getOptionsJson() ? json_decode($tree->getOptionsJson(), true) : $options;
        $this->obj = $tree;
    }
    /**
     * edit meta information
     */
    public function executeMeta()
    {
    	/* @var $tree TreeLng */
        $id = (int)$this->getRequestParameter('id', 0);
        $c = new Criteria();
        $c->add(TreeLngPeer::ID, $id);
        $c->add(TreeLngPeer::CULTURE, sfContext::getInstance()->getUser()->getCulture());
        $tree = TreeLngPeer::doSelectOne($c);
        $this->forward404Unless($tree);
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $this->updateMetaFromRequest($tree);
            /* TODO: add more fields for meta information*/
            $tree->save();
            $this->setFlash('success', 'Data was saved successfully!');
            
            
            return $this->redirect('tree/meta?id=' . $id);
        }
        $this->meta = $tree->getMetaJson() ? json_decode($tree->getMetaJson(), true) : array();
        $this->obj = $tree;
    }
    /**
     * main action, forvards layout menu links
     */
    public function executePage()
    {
    	$id = (int)$this->getRequestParameter('id', 0);
    	$tree = TreePeer::retrieveByPK($id);
    	$this->forward404Unless($tree);
    	/* $var $tree Tree */
    	// TODO: TreeLngPeer::doSelectOne => method
    	$c= new Criteria();
    	$c->add(TreeLngPeer::ID, $id);
    	$c->add(TreeLngPeer::CULTURE, sfContext::getInstance()->getUser()->getCulture());
    	$treeLng = TreeLngPeer::doSelectOne($c);
        $response = $this->getResponse();
        if( $treeLng )
        {
        	$arMeta = json_decode($treeLng->getMetaJson(), true);
        	if(!empty($arMeta['description']))
        	{
        		$response->addMeta('description', $arMeta['description']);
        	}
            if(!empty($arMeta['keywords']))
            {
                $response->addMeta('keywords', $arMeta['keywords']);
            }
            $response->setTitle($treeLng->getMetaTitle());
        }
        $link = '';
        switch ($tree->getObjType()) {
            case MyConstants::TYPE_GALLERY:
                return $this->forward('gallery'
                                  , 'display'
                                  , array('id' => $tree->getObjId()));
                break;
            case MyConstants::TYPE_TEXTMODULE:
                return $this->forward('textmodule'
                                  , 'page'
                                  , array('id' => $tree->getId()));
                break;
            case MyConstants::TYPE_CATEGORY:
                return $this->forward('product'
                                  , 'list');
                break;
            case MyConstants::TYPE_LINK_TO:
                $forvardParameters = $tree->returnUrl();
                $request = $this->getRequest();
                Tree::setRequestParameters($request, $forvardParameters->getParameters());
                return $this->forward($forvardParameters->getModule()
                                    , $forvardParameters->getAction());
                break;
        }
    }
    
    public function updateMetaFromRequest($tree)
    {
        $meta =  array();
            if( ($title = $this->getRequestParameter('meta_title')) )
            {
                $tree->setMetaTitle($title);
            }
            if(($description = $this->getRequestParameter('meta[description]')))
            {
                $meta['description'] = $description;
            }
            if(($keywords = $this->getRequestParameter('meta[keywords]')))
            {
                $meta['keywords'] = $keywords;
            }
            $tree->setMetaJson(json_encode($meta));
    }
    
    public function executeChange()
    {
        $objId = (int)$this->getRequestParameter('id', 0);
        $obj = TreePeer::retrieveByPk($objId);
        $this->forward404Unless($obj);
        // Delete old module files
        /* @var $obj Tree */
        Tree::deleteObjByType($obj->getObjType(), $objId);
        $moduleType = $this->getRequestParameter('module_type');
        $moduleId = 0;

        $arrTree = Tree::getTreeLng(array($obj->getId()), $this->getUser()->getCulture());
        switch( $moduleType )
        {
            case MyConstants::TYPE_GALLERY:
                $moduleType = MyConstants::TYPE_GALLERY;
                $gallery = Gallery::getNewOrUnused($obj->getId(), get_user_id());
                /* @var $gallery Gallery */
                $gallery->setName($arrTree[$obj->getId()]->getName());
                $gallery->save();
                $moduleId  = $gallery->getId();
                break;
            case MyConstants::TYPE_TEXTMODULE:
                $moduleType = MyConstants::TYPE_TEXTMODULE;
                $text_module = TextModule::getNewOrUnused(get_user_id());
                //debugvar($text_module);
                $text_module->setUserId(get_user_id());
                $text_module->setName($arrTree[$obj->getId()]->getName());
                $text_module->save();
                $moduleId = $text_module->getId();
                break;
            case MyConstants::TYPE_CATEGORY:
                /* @var $category Category */
                $moduleType = MyConstants::TYPE_CATEGORY;
                $category = new Category();
                $category->setCulture($this->getUser()->getCulture());
                $category->setUserId(get_user_id());
                $category->setName($arrTree[$obj->getId()]->getName());
                $category->setStatusId(MyConstants::STATUS_NEW);
                $category->save();
                $moduleId = $category->getId();
                break;
            case MyConstants::TYPE_LINK_TO:
                $this->redirect('tree/linkto?id=' . (int)$this->getRequestParameter('id'));
                break;
            default:
                $moduleType = MyConstants::MODULE_VIRTUAL;
                break;
        }

        $obj->setObjType($moduleType);
        $obj->setObjId($moduleId);
        $obj->save();

        $this->redirect('tree/settings?id=' . $obj->getId());
    }


    public function executeSettings()
    {
        $userId = $this->getUser()->getAttribute('userId');
        $this->forwardUnless($userId, 'system', 'login');
        $objId = (int)$this->getRequestParameter('id', 0);

        if( $objId )
        {
            $obj = TreePeer::retrieveByPk($objId);
            switch( $obj->getObjType() )
            {
                case MyConstants::TYPE_TEXTMODULE:
                    $this->redirect('textmodule/edit?id=' . $obj->getObjId());
                    break;
            }
        }

        $this->redirect('tree/list');
    }

    public function handleErrorSaveLabel()
    {
        $this->forward('tree', 'label');
    }

    public function executeLabel()
    {
        $userId = $this->getUser()->getAttribute('userId');
        $this->forwardUnless($userId, 'system', 'login');
        $objId = (int)$this->getRequestParameter('id', 0);

        if( $objId )
        {
            $this->obj = TreePeer::retrieveByPk($objId);
        }else
            $this->obj = new Tree();
    }

    public function executeSaveSettings()
    {
        $userId = $this->getUser()->getAttribute('userId');
        $this->forwardUnless($userId, 'system', 'login');
        $objId = (int)$this->getRequestParameter('id', 0);

        if( $objId )
        {
            $obj = TreePeer::retrieveByPk($objId);
            $this->forward404Unless($obj);

            $text_module = TextModulePeer::retrieveByPk($obj->getObjId());
            $this->forwardIf($userId != $text_module->getUserId(), 'xxx', 'yyy');

            if( ($text_module->getId()) && ($objToUp = (int)$this->getRequestParameter('files[obj_to_up]')) )
            {

                $c = new Criteria();
                $c->add(FilesPeer::OBJ_ID, $text_module->getId());
                $c->add(FilesPeer::USER_ID, $text_module->getUserId());
                APriority::moveUp($c, $objToUp);

            }

            //$obj->setLabel($label);
            //debugvar($text_module);

            $fileName = $this->getRequest()->getFileName('text_module[new_photo]');
            $filePath = $this->getRequest()->getFilePath('text_module[new_photo]');
            //debugvar($filePath . ' -&gt; ' . sfConfig::get('sf_web_dir') . '/' . sfConfig::get('app_images_dir') . '/' . sfConfig::get('app_gallery_dir'));
            if( !empty($filePath) )
            {
                Files::saveTo($fileName, $filePath, $text_module->getId(), $text_module->getUserId(), $obj->getObjType());
            }

            //exit('saving...');
            //$obj->setStatus(MyConstants::AdStatusApproved);
            //$obj->save();
            //$this->setFlash('notice', 'Label is saved');
        }

        $this->redirect('tree/settings?id=' . $objId);
    }

    public function executeSaveLabel()
    {
        $objId = (int)$this->getRequestParameter('id', 0);
        $label = strip_tags($this->getRequestParameter('tree[label]', ''));

        if( $objId )
        {
            $obj = TreePeer::retrieveByPk($objId);
            $this->forward404Unless($obj);
            $obj->setLabel($label);
            //debugvar($obj);
            //exit('saving...');
            $obj->save();
            $this->setFlash('notice', 'Label is saved');
        }else
            $this->setFlash('error', 'Label is not saved!');

        $this->redirect('tree/list');
    }

    public function executeSetLng()
    {
        $lng = User::getValidCultureOrDefault($this->getRequestParameter('lng'));
        //debugvar('Culture to set is: ' . $lng);
        //exit();
        $this->getUser()->setCulture($lng);
        $this->redirect('tree/list');
    }

    public function executeList()
    {
        $this->processSort();

        //$this->processFilters();


        // pager
        $this->pager = new sfPropelPager('Tree', 20);
        $c = new Criteria();
        $c->add(TreePeer::PARENT_ID, 0);
        $this->addSortCriteria($c);
        //$this->addFiltersCriteria($c);
        $this->pager->setCriteria($c);
        $this->pager->setPage($this->getRequestParameter('page', 1));
        $this->pager->init();
    }

    public function executeCreate()
    {
        $parentId = (int)$this->getRequestParameter('tree_parent_id', 0);
        if( $parentId )
        {
            $this->parent = TreePeer::retrieveByPk($parentId);
            //debugvar($this->parent);
            //exit('creating...');
        }else
            $this->parent = new Tree();

        $this->labels = $this->getLabels();
        $this->tree = new Tree();
        $this->tree->setParentId($this->parent->getId());
        $this->setTemplate('edit');
        //parent::executeEdit();
    }

    public function executeEdit()
    {
        $parentId = (int)$this->getRequestParameter('id', 0);
        if( $parentId )
        {
            $this->parent = TreePeer::retrieveByPk($parentId);
            //$arLng = Tree::getTreeLng(array($parentId), $this->getUser()->getCulture());
            //if( !empty( $arLng[$this->parent->getId()] ) )
            //    $this->parent->setName($arLng[$this->parent->getId()]->getName());
            //debugvar($arLng);
            //debugvar($this->parent);
            //exit();
        }else
            $this->parent = new Tree();

        parent::executeEdit();
    }

    protected function saveTree($tree)
    {
        if( $tree->getParentId() )
        {
            $parent = TreePeer::retrieveByPk($tree->getParentId());
            $c = new Criteria();
            $c->add(TreePeer::PARENT_ID, $tree->getParentId());
            $parent->setChildrenQnt(TreePeer::doCount($c));

            // Add new child if this is new item
            if( !$tree->getId() )
                $parent->setChildrenQnt($parent->getChildrenQnt() + 1);

            //debugvar($parent);
            $tree->setBranch($parent->getBranch() . $parent->getId() . ':');
            //debugvar($tree);
            //exit('saving...');
            $parent->save();
        }

        $tree->save();
        $tree->saveLng($this->getUser()->getCulture());
        //$tree->setName($this->getRequestParameter('tree[name]'), $this->getUser()->getCulture());
    }

    protected function deleteTree($tree)
    {
        /* @var $parent Tree */
        // reduce children quantity by parent
        $parent = TreePeer::retrieveByPK($tree->getParentId());
        if($parent)
        {
            $parent->setChildrenQnt($parent->getChildrenQnt() - 1);
            $parent->save();
        }
        // Delete all children
        if( $tree->getChildrenQnt() )
        {
            //$arBranch = Tree::getTree($tree->getId());
            $arPks = Tree::getTreeIds($tree->getId());
            $c = new Criteria();
            $c->add(TreePeer::ID, $arPks, Criteria::IN);
            TreePeer::doDelete($c);
            //delete values from lng table too
            $clng = new Criteria();
            $clng->add(TreeLngPeer::ID, $arPks, Criteria::IN);
            TreeLngPeer::doDelete($clng);
        }
        $tree->delete();
    }


    protected function getTreeOrCreate($id = 'id')
    {
        $tree = parent::getTreeOrCreate($id);
        $parentId = (int)$this->getRequestParameter('tree[parent_id]', 0);
        if( $parentId )
            $tree->setParentId($parentId);

        $arLng = Tree::getTreeLng(array($tree->getId()), $this->getUser()->getCulture());
        if( !empty( $arLng[$tree->getId()] ) )
            $tree->setName($arLng[$tree->getId()]->getName());

        //debugvar($tree);
        //exit('getTreeOrCreate()...');

        return $tree;
    }
/*
    protected function updateTreeFromRequest()
    {
        $tree = $this->getRequestParameter('tree');

        if (isset($tree['parent_id']))
        {
            $this->tree->setParentId($tree['parent_id']);
        }
    
        if (isset($tree['name']))
        {
            //$this->tree->setName($tree['name'], $this->getUser()->getCulture());
        }
    }
*/
}
